import {Component, OnInit, ViewEncapsulation, Input} from '@angular/core';
import {TutorialService} from 'src/app/service/tutorialService';
import {CollectionService} from 'src/app/service/collectionService';
import {EventEmitService} from 'src/app/service/EventEmitService';
import {CookieService} from 'ngx-cookie-service';
import {DatePipe} from '@angular/common';
import {MessageService} from 'primeng/api';

@Component({
    selector: 'app-tutorial-editable-content',
    templateUrl: './tutorial-editable-content.component.html',
    styleUrls: ['./tutorial-editable-content.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class TutorialEditableContentComponent implements OnInit {

    @Input() tutorialName: string;
    collectionId: number;
    data: any[];
    fileOrFolder: any[] = [
        {label: '文件', value: 'file'},
        {label: '文件夹', value: 'folder'}
    ];
    choice = 'file';
    name: string;
    selectedFile: any;
    editAuth = false;
    selectNode: any;
    addFolderDisplay = false;

    constructor(private tutorialService: TutorialService,
                private collectionService: CollectionService,
                private eventEmitService: EventEmitService,
                private cookieService: CookieService,
                private datePipe: DatePipe,
                private msgService:MessageService) {
    }

    ngOnInit(): void {
        if (this.tutorialName === this.cookieService.get('username') + '-blog') {
            this.editAuth = true;
        } else if (this.cookieService.get('auth').indexOf('tutorial') !== -1 && this.tutorialName.indexOf("教程") != -1) {
            this.editAuth = true;
        } else {
            this.editAuth = false;
        }
        console.log(this.tutorialName);
        if (this.tutorialName !== '-blog') {
            this.collectionService.getCollectionByName(this.tutorialName).subscribe(result => {
                console.log(result);
                this.collectionId = result.id;
                this.data = eval(result.content);
                console.log(this.data);
            });
        }
    }

    addFolder(event: any, node: any) {
        this.selectNode = node;
        this.addFolderDisplay = true;
    }

    deleteFolder(node: any) {
        this.selectNode = node;
        this.deleteMdFileInBatch(this.getDeletedFileIds(node));
        this.DFSDelete(this.data[0], node);
        this.updateCollection();
    }

    deleteMdFileInBatch(fileIds: number[]){
        this.tutorialService.deleteMarkdownFiles(fileIds).subscribe(response=>{
            this.msgService.add({severity:'success', summary: '删除成功', detail:'删除成功'});
        });
    }

    getDeletedFileIds(node){
        let fileIds:number[] = [];
        let q: number[] = [node];
        while(q.length > 0){
            let node:any = q.shift();
            if(node.children == null){
                fileIds.push(node.id);
            }
            else{
                for(let i = 0; i < node.children.length; i++){
                    q.push(node.children[i]);
                }
            }
        }
        return fileIds;
    }

    DFSDelete(root, node) {
        if (root.children == null) {
            return;
        }
        for (let i = 0; i < root.children.length; i++) {
            if (root.children[i] === node) {
                if (root.children.length === 1) {
                    root.children = [];
                } else {
                    // delete root.children[i];
                    root.children.splice(i, 1);
                }
                return;
            } else {
                this.DFSDelete(root.children[i], node);
            }
        }
    }


    saveContentItem() {
        this.reConstructData();
        this.addFolderDisplay = false;
    }

    reConstructData() {
        if (this.choice === 'file') {
            // get author
            const author  = this.cookieService.get('username');
            const date = this.datePipe.transform(new Date(),'yyyy-MM-dd hh:mm:ss');
            this.tutorialService.generateNewMarkdownFile(this.name, author, date ).subscribe(id => {
                this.selectNode.children.push({
                    id,
                    label: this.name,
                    icon: 'pi pi-file'
                });
                this.choice = 'file';
                this.name = '';
                this.updateCollection();
            });
        } else {
            this.selectNode.children.push({
                label: this.name,
                expandedIcon: 'pi pi-folder-open',
                collapsedIcon: 'pi pi-folder',
                children: []
            });
            this.choice = 'file';
            this.name = '';
            this.updateCollection();
        }
    }


    updateCollection() {
        // tslint:disable-next-line:only-arrow-functions
        const handleCircular = function() {
            const cache = [];
            const keyCache = [];
          // tslint:disable-next-line:only-arrow-functions
            return function(key, value) {
                if (typeof value === 'object' && value !== null) {
                    const index = cache.indexOf(value);
                    if (index !== -1) {
                        return '[Circular ' + keyCache[index] + ']';
                    }
                    cache.push(value);
                    keyCache.push(key || 'root');
                }
                return value;
            };
        };

        const tmp = JSON.stringify;
      // tslint:disable-next-line:only-arrow-functions
        JSON.stringify = function(value, replacer, space) {
            replacer = replacer || handleCircular();
            return tmp(value, replacer, space);
        };
        const collection: any = {
            id: this.collectionId,
            name: this.tutorialName,
            content: JSON.stringify(this.data)
        };
        console.log(JSON.stringify(this.data));
        this.collectionService.updateCollectionById(collection).subscribe(result => {
            console.log(result);
        });

        JSON.stringify = tmp;
    }

    cancel() {
        this.addFolderDisplay = false;
        this.choice = 'file';
        this.name = '';
    }

    nodeSelect(event) {
        // console.log(this.selectedFile);
        if (this.selectedFile.children == null) {
            console.log('emit a fiel id:');
            console.log(this.selectedFile.id);
            this.eventEmitService.markdownfileEventer.emit(this.selectedFile.id);
        }
        // console.log(event);
    }

    nodeUnselect(event) {
        // console.log(event);
    }
}
